/*
Copyright 2018 Embedded Microprocessor Benchmark Consortium (EEMBC)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Original Author: Shay Gal-on
*/
#include "coremark.h"
#include "core_portme.h"

#include "clock_config.h"
#include "fsl_iocon.h"
#include "fsl_clock.h"
#include "fsl_usart.h"
#include "fsl_gpio.h"

/* Porting: macros. */

/* CoreMark要求程序运行的最短时间至少是10s,
 * 根据使用的系统时钟等情况，可以在此处修改迭代次数. */
#define ITERATIONS 800

/* 本文件使用systick作为定时器, 在systick中断中返回systick_count的值,
 * 这个值每1ms递增一次, 也就是说, 每秒钟会更新1000次时钟计数值. */
/* 在iar下会引入一个timer32.h头文件, 其中包含了CLOCKS_PER_SEC的定义. */
#if defined(CLOCKS_PER_SEC)
#undef CLOCKS_PER_SEC
#endif /* CLOCKS_PER_SEC */

#define CLOCKS_PER_SEC 1000

#if VALIDATION_RUN
    volatile ee_s32 seed1_volatile=0x3415;
    volatile ee_s32 seed2_volatile=0x3415;
    volatile ee_s32 seed3_volatile=0x66;
#endif
#if PERFORMANCE_RUN
    volatile ee_s32 seed1_volatile=0x0;
    volatile ee_s32 seed2_volatile=0x0;
    volatile ee_s32 seed3_volatile=0x66;
#endif
#if PROFILE_RUN
    volatile ee_s32 seed1_volatile=0x8;
    volatile ee_s32 seed2_volatile=0x8;
    volatile ee_s32 seed3_volatile=0x8;
#endif
    volatile ee_s32 seed4_volatile=ITERATIONS;
    volatile ee_s32 seed5_volatile=0;

/* Porting : Timing functions
    How to capture time and convert to seconds must be ported to whatever is supported by the platform.
    e.g. Read value from on board RTC, read value from cpu clock cycles performance counter etc.
    Sample implementation for standard time.h and windows.h definitions included.
*/

/**********************************************************************************************/
volatile uint32_t systick_count = 0u;
void SysTick_Handler(void)
{
    systick_count++;

    /* 这里每秒闪烁2次LED灯, 只是为了让等待不再寂寞.
    * 10秒钟以上板子没有任何反应会让用户感觉很不好. */
    if ( 0u == (systick_count % (CLOCKS_PER_SEC /4u)) )
    {
        GPIO_PortToggle(GPIO, 1u, 1u << 6u); /* pio1_6, led_red. */
    }
}
/**********************************************************************************************/
/* 下面的函数都是coremark模板中自带的,
 * 进行移植时尽量用自定义的函数去适配, 而不是直接换掉. */

/* 直接从硬件读取当前的时间计数值. */
CORETIMETYPE barebones_clock()
{
    //#error "You must implement a method to measure time in barebones_clock()! This function should return current time.\n"
    return systick_count;
}

/* Define : TIMER_RES_DIVIDER
    Divider to trade off timer resolution and total time that can be measured.

    Use lower values to increase resolution, but make sure that overflow does not occur.
    If there are issues with the return value overflowing, increase this value.
    */
#define GETMYTIME(_t) (*_t=barebones_clock())
#define MYTIMEDIFF(fin,ini) ((fin)-(ini))
#define TIMER_RES_DIVIDER 1
#define SAMPLE_TIME_IMPLEMENTATION 1
#define EE_TICKS_PER_SEC (CLOCKS_PER_SEC / TIMER_RES_DIVIDER)

/** Define Host specific (POSIX), or target specific global time variables. */
static CORETIMETYPE start_time_val, stop_time_val;

/* Function : start_time
    This function will be called right before starting the timed portion of the benchmark.

    Implementation may be capturing a system timer (as implemented in the example code)
    or zeroing some system parameters - e.g. setting the cpu clocks cycles to 0.
*/
void start_time(void) {
    GETMYTIME(&start_time_val );
}
/* Function : stop_time
    This function will be called right after ending the timed portion of the benchmark.

    Implementation may be capturing a system timer (as implemented in the example code)
    or other system parameters - e.g. reading the current value of cpu cycles counter.
*/
void stop_time(void) {
    GETMYTIME(&stop_time_val );
}
/* Function : get_time
    Return an abstract "ticks" number that signifies time on the system.

    Actual value returned may be cpu cycles, milliseconds or any other value,
    as long as it can be converted to seconds by <time_in_secs>.
    This methodology is taken to accomodate any hardware or simulated platform.
    The sample implementation returns millisecs by default,
    and the resolution is controlled by <TIMER_RES_DIVIDER>
*/
CORE_TICKS get_time(void) {
    CORE_TICKS elapsed=(CORE_TICKS)(MYTIMEDIFF(stop_time_val, start_time_val));
    return elapsed;
}
/* Function : time_in_secs
    Convert the value returned by get_time to seconds.

    The <secs_ret> type is used to accomodate systems with no support for floating point.
    Default implementation implemented by the EE_TICKS_PER_SEC macro above.
*/
secs_ret time_in_secs(CORE_TICKS ticks) {
    secs_ret retval=((secs_ret)ticks) / (secs_ret)EE_TICKS_PER_SEC;
    return retval;
}

ee_u32 default_num_contexts=1;

/* Function : portable_init
    Target specific initialization code
    Test for some common mistakes.
*/
/* 实现对运行平台硬件层面上的初始化, 这个函数将在coremark_main.c文件中调用.
 * - 初始化内核时钟系统
 * - 初始化用于计时的systick定时器
 * - 初始化用于打印输出信息的uart串口. ee_printf()函数的实现在专门的ee_printf.c文件中.
 * - 初始化不让人寂寞的led灯
 */
void portable_init(core_portable *p, int *argc, char *argv[])
{
    //#error "Call board initialization routines in portable init (if needed), in particular initialize UART!\n"

    /***************************************************************/
    /* board hardware initialization start. */

    //BOARD_InitPins();
    BOARD_BootClockPLL150M();

    /* pins. */
    CLOCK_EnableClock(kCLOCK_Iocon);
    CLOCK_EnableClock(kCLOCK_Gpio1);
    uint32_t iocon_pin_config;
    iocon_pin_config = IOCON_PIO_FUNC(0x1) | IOCON_PIO_MODE(0x2) | IOCON_PIO_DIGIMODE_MASK;
    IOCON_PinMuxSet(IOCON, 0u, 29u, iocon_pin_config); /* pio0_29: uart0_rx. */
    iocon_pin_config = IOCON_PIO_FUNC(0x1) | IOCON_PIO_MODE(0x0) | IOCON_PIO_DIGIMODE_MASK;
    IOCON_PinMuxSet(IOCON, 0u, 30u, iocon_pin_config); /* pio0_30: uart0_tx. */
    iocon_pin_config = IOCON_PIO_FUNC(0x0) | IOCON_PIO_MODE(0x0) | IOCON_PIO_DIGIMODE_MASK;
    IOCON_PinMuxSet(IOCON, 1u, 6u, iocon_pin_config); /* pio1_6: led_red. */

    /* uart0. */
    CLOCK_AttachClk(kFRO12M_to_FLEXCOMM0);/* attach 12 MHz clock to FLEXCOMM0 (debug console) */
    usart_config_t usart_config;
    memset(&usart_config, 0, sizeof(usart_config));
    usart_config.baudRate_Bps         = 115200; /* 波特率. */
    usart_config.parityMode           = kUSART_ParityDisabled;
    usart_config.stopBitCount         = kUSART_OneStopBit;
    usart_config.bitCountPerChar      = kUSART_8BitsPerChar;
    usart_config.loopback             = false;
    usart_config.enableRx             = true;
    usart_config.enableTx             = true;
    usart_config.txWatermark          = kUSART_TxFifo0;
    usart_config.rxWatermark          = kUSART_RxFifo1;
    usart_config.syncMode             = kUSART_SyncModeDisabled;
    usart_config.enableContinuousSCLK = false;
    usart_config.clockPolarity        = kUSART_RxSampleOnFallingEdge;
    USART_Init((USART_Type *)USART0, &usart_config, CLOCK_GetFreq(kCLOCK_Fro12M));

    /* led. */
    gpio_pin_config_t gpio_pin_config;
    gpio_pin_config.pinDirection = kGPIO_DigitalOutput;
    gpio_pin_config.outputLogic = 1u;
    GPIO_PinInit(GPIO, 1u, 6u, &gpio_pin_config);

    /* systick for timer. */
    SysTick_Config(CLOCK_GetSystickClkFreq(0) / 1000u); /* using core0's systick, 1ms per tick. */

    /* board hardware ready. */
    /***************************************************************/

    ee_printf("\nhello, this is eembc coremark\n\n");

    /* coremark routines. */
    if (sizeof(ee_ptr_int) != sizeof(ee_u8 *)) {
        ee_printf("ERROR! Please define ee_ptr_int to a type that holds a pointer!\n");
    }
    if (sizeof(ee_u32) != 4) {
        ee_printf("ERROR! Please define ee_u32 to a 32b unsigned type!\n");
    }
    p->portable_id=1;
}
/* Function : portable_fini
    Target specific final code
*/
/* coremark程序执行完毕后, 执行此函数. */
void portable_fini(core_portable *p)
{
    p->portable_id=0;

    ee_printf("\ndone\n");
}

/* 通过串口打印log信息的底层函数实现. */
void ee_putc(char c)
{
//#error "You must implement the method ee_putc() to use this file!\n";
/*  Output of a char to a UART usually follows the following model:
    Wait until UART is ready
    Write char to UART
    Wait until UART is done

    Or in code:
    while (*UART_CONTROL_ADDRESS != UART_READY);
    *UART_DATA_ADDRESS = c;
    while (*UART_CONTROL_ADDRESS != UART_READY);

    Check the UART sample code on your platform or the board documentation.
*/
    if (c == '\n')
    {
        uint8_t ch = '\r';
        USART_WriteBlocking((USART_Type *)USART0, (uint8_t *)&ch, 1u);
    }
    USART_WriteBlocking((USART_Type *)USART0, (uint8_t *)&c, 1u);
}

/* EOF. */

